<?php
/*
 * app接口文件
 */
namespace Home\Controller;
use Think;
use User\Api\UserApi;

class ApiController extends HomeController{
    function __construct(){
        parent::__construct();
        $this->param = $this->jsondecode(); 
    }

    public function getTypeList(){
        $page = "{$this->param['page_start']},{$this->param['pagesize']}";
        $null = true;
        if(!empty($this->param['uid'])){
            $type = M("membercard")->where("uid={$this->param['uid']}")->group('type_id')->field('type_id')->select();
            if(count($type) > 0){
                $null = false;
                $str = $type[0]['type_id'];
                for($i = 1; $i < count($type); $i++){
                    $str .= ",".$type[$i]['type_id'];
                }
                $where = array("one_type.type_id"=>array("in",$str),"one_type.zhutui"=>1,"_logic"=>"OR");
                $field = "one_type.name as type_name,one_type.*,m.id,m.cardnum,m.mobile,m.flag";
                $list = M('type')->where($where)->join("LEFT JOIN one_membercard m on m.type_id=one_type.type_id and m.uid={$this->param['uid']}")->field($field)->limit($page)->select();
            }
        }

        if($null){
            $type = M('shop')->group('type_id')->field('type_id')->select();
            $str = $type[0]['type_id'];
            for($i = 1; $i < count($type); $i++){
                $str .= ",".$type[$i]['type_id'];
            }
            $where = array("type_id"=>array("in",$str),"zhutui"=>1,"is_private"=>0);
            $list = M('type')->where($where)->field(" *,name as type_name ")->limit($page)->select();
        }

        $data = array();
        foreach ($list as $key => $value) {
            $tmp = array();
            $tmp['type_id']   = $value['type_id'];
            $tmp['type_name'] = $value['type_name'];
            $tmp['type_logo'] = $value['shop_logo_image'] == -1 ? "":get_cover($value['shop_logo_image'],'path');
            $tmp['is_member'] = $value['id'] ? 1:0;
            $tmp['cardnum']   = $value['cardnum'] ? $value['cardnum'] : '';
            $tmp['mobile']   = $value['mobile'] ? $value['mobile'] : '';
			$tmp['shop_color']   = $value['shop_color'];
            $tmp['flag']   = empty($value['flag'])? 0:$value['flag'];
            $data[] = $tmp;
        }

        $this->success('success',$data);
    }

    public function getAlltype(){
        $type = M('shop')->group('type_id')->field('type_id')->select();
        $str = $type[0]['type_id'];
        for($i = 1; $i < count($type); $i++){
            $str .= ",".$type[$i]['type_id'];
        }
        $list = M('type')->where("type_id in ($str) AND is_private=0")->select();

        $data = array();
        foreach ($list as $key => $value) {
            $tmp = array();
            $tmp['type_id']   = $value['type_id'];
            $tmp['type_name'] = $value['name'];
            $tmp['type_logo'] = get_cover($value['shop_logo_image'],'path');
            $tmp['shop_color']   = $value['shop_color'];

            $data[] = $tmp;
        }
        $this ->success("success",$data);
    }

    public function getTypeInfo(){
        $type_info = M('type')->find($this->param['type_id']);
        $card = M('membercard')->where(array("uid"=>$this->param['uid'],"type_id"=>$this->param['type_id']))->find();

        $info = array(
            'card_id'         => $card['id'],
            'type_id'         => $type_info['type_id'],
            'type_name'       => $type_info['name'],
            'type_card_image' => $type_info['shop_cart_image'] == -1 ? "":get_cover($type_info['shop_cart_image'],'path'),
            'cardnum'         => empty($card['cardnum']) ? '' : $card['cardnum'],
            'mobile'          => empty($card['mobile']) ? '' : $card['mobile'],
            'point'           => empty($card['point']) ? '' : $card['point'],
            'is_private'      => $type_info['is_private']
            );
        $list = M('shop')->where("type_id=".$this->param['type_id'])->field("id as sid,shop_name,shop_addr")->select();
        
        $list = $list ? $list : array();

        $data = array("info"=>$info,"list"=>$list);

        $this->success("success",$data);
    }

    public function getPromotion(){
        $promotion = M('salespromotion')->where("sid=".$this->param['sid'])->limit("{$this->param['page_start']},{$this->param['pagesize']}")->select();
        if($promotion){
            foreach ($promotion as $key => $value) {
                $tmp = $value;
                $tmp['imageurl'] = get_cover($value["promotionimage"],'path');
                $data[] = $tmp; 
            }
        }else{
            $data = array();
        }
        $this->success("success",$data);
    }

    public function bindmembers(){
        $m = M("membercard");
        $memberinfo = $m->where(array("type_id"=>$this->param['type_id'],"uid"=>$this->param['uid']))->find();
        if(!$memberinfo){
            $data = $this->param;
            $data['add_time'] = NOW_TIME;
            $data['cartid'] = md5(NOW_TIME.rand(100,999));

            $r = $m->add($data);
            if($r){
                $this->success("绑定成功");
            }else{
                $this->error("绑定失败请重新绑定");
            }
        }else{
            $this->error("已经绑定会员卡");
        }
    }
    public function getCouponList(){
        $coupon = M('coupon_data');
        $where = "one_coupon_data.uid=".$this->param['uid'];
        $field = "one_coupon_data.id as static_id,one_coupon_data.times as static_times,one_coupon_data.status as static_status,one_coupon_data.*,one_coupon.*,one_shop.shop_name,one_type.shop_color";
        $join_coupon = "LEFT JOIN one_coupon on one_coupon.id=one_coupon_data.coupon_id";
        $join_shop = "LEFT JOIN one_shop on one_coupon_data.shop_id=one_shop.id";
        $join_type = "LEFT JOIN one_type on one_shop.type_id=one_type.type_id";
        $limit = "{$this->param['page_start']},{$this->param['pagesize']}";

        $list = $coupon->where($where)->join($join_coupon)->join($join_shop)->join($join_type)->field($field)->order("addtime DESC")->select();
        $data = array();
        foreach ($list as $key => $value) {
            $tmp = array(
                'id' => $value['static_id'],
                'code' => $value['code'],
                'title' => $value['title'],
                'type' => $value['type'],
                'image' => empty($value['imgurl'])?"":$value['imgurl'],
                'addtime' => $this->TimeFormat($value['addtime']),
                'starttime' => $this->TimeFormat($value['starttime']),
                'endtime' => $this->TimeFormat($value['endtime']),
                'times_leave' => $value['static_times'],
                'times_total' => $value['times'],
                'dikou' => $value['dikou'],
                'jianmian' => $value['jianmian'],
                'status' => $value['static_status'],
                'sumtime' => empty($value['sumtime'])? "" : $this->TimeFormat($value['sumtime']),
                'deadtime' => $this->TimeFormat($value['endtime'],-1) . "过期",
                'shop_name' => $value['shop_name'],
                'color' => $value['shop_color']
                );

            $data[] = $tmp;
        }
        $this->success("",$data);
    }
    public function tickCoupon(){
        $coupon = M('coupon');
        $info = $coupon->find($this->param['coupon_id']);
        if($info){
            if($info['endtime'] < NOW_TIME) $this->error('卡券已过期');
            if($info['total'] < 1) $this->error('卡券已全部被领取');
            $has_ticked = M('coupon_data')->where(array("uid"=>$this->param['uid'],"coupon_id"=>$this->param['coupon_id']))->find();
            if(is_array($has_ticked)) $this->error("已经领取过该优惠券，无法重复领取");

            $num = empty($this->param['num'])? 1:$this->param['num'];
            if($num > $info['get_limit']) $num = $info['get_limit'];
            $num = (int)$num > 0 ? (int)$num : 1;

            $coupon->where("id=".$this->param['coupon_id'])->setDec('total',$num);

            $data = array(
                'coupon_id' => $info['id'],
                'shop_id'   => $info['shop_id'],
                'addtime'   => NOW_TIME,
                'status'    => 0,
                'uid'       => $this->param['uid'],
                'nickname'  => $this->param['nickname'],
                'times'     => $info['times']
                );
            if(M('coupon_data')->add($data)){
                $this->success("领取成功");
            }else{
                $this->error("领取失败，请重新领取");
            }
        }else{
            $this->error("卡券不存在");
        }
    }
    public function getAllCoupon(){
        $where = array('total'=>array('gt',0),'endtime'=>array('gt',NOW_TIME));
        if(!empty($this->param['shop_id']) && $this->param['shop_id'] != '0'){
            $where['shop_id'] = $this->param['shop_id'];
        }
        $field = "*,(select count(*) from one_coupon_data d where d.uid={$this->param['uid']} and d.coupon_id=one_coupon.id) as has_ticked";
        $list = M('coupon')->where($where)->field($field)->order("id DESC")->select();

        $this->success("",$list);
    }

    public function jifenList(){
        $list = M('jifenduihuan')->where("sid=".$this->param['sid'])->limit("{$this->param['page_start']},{$this->param['pagesize']}")->select();
        if($list){
            foreach ($list as $key => $value) {
                $tmp = $value;
                $tmp['imageurl'] = get_cover($value["promotionimage"],'path');
                $data[] = $tmp; 
            }
        }else{
            $data = array();
        }
        $this->success("success",$data);
    }

    public function appUpdate(){
        $this->success("success",M('app_update')->where("id=1")->find());
    }

    public function delMemberCard(){
        $where = array("uid"=>$this->param['uid'],'type_id'=>$this->param['type_id']);
        if(M('membercard')->where($where)->delete()){
            $this->success("删除成功");
        }else{
            $this->error('删除失败');
        }
    }

    public function editMemberCard(){
        $where = array("uid"=>$this->param['uid'],'type_id'=>$this->param['type_id']);
        if(M('membercard')->where($where)->save($this->param['data'])){
            $this->success("修改成功");
        }else{
            $this->error('修改失败');
        }
    }
    public function getMemberCardInfo(){
        $info = M('membercard')->where(array("uid"=>$this->param['uid'],'type_id'=>$this->param['type_id']))->find();
        if($info){
            $this->success("success",$info);
        }else{
            $this->error("卡片不存在");
        }
    }

    public function addBrowseLog(){
        if(empty($this->param['uid']) || empty($this->param['news_id'])) $this->error("参数不足");
        $browse = M('browselog');
        $data = array('uid'=>$this->param['uid'],'news_id'=>$this->param['news_id']);

        $r = $browse->where($data)->find();
        if(is_array($r) && !empty($r['id'])){
            // 已经有浏览记录
            $reset = array('id'=>$r['id'],'browsetime'=>NOW_TIME,'browsecount'=>array('exp', 'browsecount+1'));
            $res = $browse->save($reset);
        }else{
            // 尚未产生浏览记录
            $data['browsetime'] = NOW_TIME;
            $res = $browse->add($data);
        }
        if($res){
            $this->success("success");
        }else{
            $this->error($browse->getError());
        }
    }

    public function getBrowseLog(){
        if(empty($this->param['uid'])) $this->error("参数不足");

        $limit = "{$this->param['page_start']},{$this->param['pagesize']}";
        $join = "LEFT JOIN one_document d ON one_browselog.news_id = d.id";
        $list = M('browselog')->where("one_browselog.uid={$this->param['uid']}")->join($join)->order("browsetime DESC")->join("LEFT JOIN one_document_article a ON one_browselog.news_id = a.id")->limit($limit)->select();
        $data = array();
        foreach ($list as $key => $value) {
            $tmp = $value;
            $image = get_cover($value['cover_id']);
            $tmp['imgurl'] = $image? $image:null;

            $data[] = $tmp;
        }

        $this->success("success",$data);
    }

    // 原始爆料方法
    // public function addBid(){
    //     if(empty($this->param['uid']) || empty($this->param['title'])) $this->error("参数不足");
    //     $data = array(
    //         'uid'=>$this->param['uid'],
    //         'bid_title'=>$this->param['title'],
    //         'bid_time'=>NOW_TIME,
    //         'bid_content'=>$this->param['content'],
    //         'mobile'=>$this->param['mobile'],
    //         'address'=>$this->param['address']
    //         ); 

    //     if($_FILES['image1']['name']){
    //         $upload = new \Think\Upload();// 实例化上传类

    //         $upload->maxSize   =     3145728 ;// 设置附件上传大小
    //         $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    //         $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
    //         $upload->savePath  =     'Bid/'; // 设置附件上传（子）目录

    //         // 上传文件 
    //         $info   =   $upload->upload();
    //         $data['bid_image_path'] = 'Uploads/'.$info['image1']['savepath'];

    //         $str = '';
    //         foreach ($info as $key => $value) {
    //             if($key == 'image1'){
    //                 $str .= $value['savename'];
    //             }else{
    //                 $str .= ",".$value['savename'];
    //             }
                
    //         }

    //         $data['bid_images'] = $str;
    //     }
    //     if(M('bid')->add($data)){
    //         $this->success("爆料成功");
    //     }else{
    //         $this->error(M()->getError());
    //     }
    // }

    // 新爆料方法  直接生成新闻
    public function addBid(){
        if(empty($this->param['uid']) || empty($this->param['title'])) $this->error("参数不足");
        if($_FILES['image1']['name']){
            $upload = new \Think\Upload();// 实例化上传类

            $upload->maxSize   =     3145728 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
            $upload->savePath  =     'Bid/'; // 设置附件上传（子）目录

            // 上传文件 
            $info   =   $upload->upload();
            $path = 'Uploads/'.$info['image1']['savepath'];

            $picture = array(
                'path' => '/Uploads/'.$info['image1']['savepath'].$info['image1']['savename'],
                'url'  => '',
                'md5'  => $info['image1']['md5'],
                'sha1' => $info['image1']['sha1'],
                'status' => 1,
                'create_time' => NOW_TIME
                );
            $img = M('picture')->add($picture);
            if(!$img) $this->error(M()->getError());

            $str = '';
            foreach ($info as $key => $value) {
                if($key == 'image1'){
                    continue;
                }else{
                    // $str .= '<img src="'.$path.$value['savename']'">';
                    $str .= "<img src='".$path.$value['savename']."' >";
                }
            }
        }

        // 创建新闻主信息
        $data = array(
            'uid'         => $this->param['uid'],
            'name'        => '',
            'title'       => $this->param['title'],
            'category_id' => 46,
            'group_id'    => 0,
            'description' => '',
            'model_id'    => 2,
            'type'        => 2,
            'cover_id'    => $img?$img:0,
            'create_time' => NOW_TIME,
            'update_time' => NOW_TIME,
            'status'      => 2
            );

        $newsid = M('document')->add($data);
        if(!$newsid) $this->error(M()->getError());

        $data_2 = array(
            'id' => $newsid,
            'parse' => 0,
            'content' => $this->param['content']."<br><br>爆料人手机号：{$this->param['mobile']}<br><br>爆料人地址：{$this->param['address']}<br>$str",
            'template' => 0,
            'video' => '',
            'localvideo' => 0
            );

        if(M('document_article')->add($data_2)){
            $this->success("爆料成功");
        }else{
            $this->error(M()->getError());
        }
    }
    // 原始爆料方法
    // public function getBid(){
    //     if(empty($this->param['uid'])) $this->error("参数不足");
    //     $this->success("success",M('bid')->where("uid={$this->param['uid']}")->limit("{$this->param['page_start']},{$this->param['pagesize']}")->select());
    // }
    public function getBid(){
        if(empty($this->param['uid'])) $this->error("参数不足");

        $list = M('document')->where(array('uid'=>$this->param['uid'],'category_id'=>46))->field("id,title,cover_id,create_time,status")->order("id DESC")->limit("{$this->param['page_start']},{$this->param['pagesize']}")->select();
        $data = array();
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $tmp = $value;
                unset($tmp['cover_id']);
                $image = get_cover($value['cover_id'],'path');
                $tmp['imgurl'] = $image ? $image : "";

                $data[] = $tmp;
            }
        }

        $this->success("success",$data);
    }

    public function addFeedback(){
        if(empty($this->param['uid'])) $this->error("参数不足");
        $data = array(
            'uid'=>$this->param['uid'],
            'fd_title'=>$this->param['title'],
            'fd_time'=>NOW_TIME,
            'fd_content'=>$this->param['content']
            ); 
        if(M('feedback')->add($data)){
            $this->success("反馈成功");
        }else{
            $this->error(M()->getError());
        }
    }

    public function addprivatecard(){
        if(empty($this->param['uid']) || empty($this->param['shop_name']) || empty($this->param['cardnum'])) $this->error('参数不足');
        $color = array("109ae4","ffeb12","1eccf8","6ade31","c770eb");
        if($_FILES['logo']['name']){
            $upload = new \Think\Upload();
            $upload->maxSize  = 3145728;
            $upload->exts     = array('jpg','gif','png','jpeg');
            $upload->rootPath = './Uploads/';
            $upload->savePath = 'Picture/';

            $info = $upload->uploadOne($_FILES['logo']);
            // ["name"]=> string(18) "login-logo-qq.jpeg" 
            // ["type"]=> string(9) "image/png" 
            // ["size"]=> int(2285) 
            // ["key"]=> int(0) 
            // ["ext"]=> string(4) "jpeg" 
            // ["md5"]=> string(32) "c46f7cb6da3c5a9d9bc7ad145745fa3b" 
            // ["sha1"]=> string(40) "a30ab900145acf424d241b824e0aaf7d0b1b7b63" 
            // ["savename"]=> string(18) "582d3f3dd0f88.jpeg" 
            // ["savepath"]=> string(19) "Picture/2016-11-17/" 
            $picture = array(
                'path' => '/Uploads/'.$info['savepath'].$info['savename'],
                'url'  => '',
                'md5'  => $info['md5'],
                'sha1' => $info['sha1'],
                'status' => 1,
                'create_time' => NOW_TIME
                );
            $img = M('picture')->add($picture);
            if(!$img) $this->error(M()->getError());
        }else{
            $img = -1;
        }
        $type = array(
                'name' => $this->param['shop_name'],
                'shop_cart_image' => $img,
                'shop_logo_image' => $img,
                'shop_color'      => $color[rand(0,4)],
                'is_private'      => 1
                );
            $type_id = M('type')->add($type);
            if(!$type_id) $this->error(M()->getError());

            $card = array(
                'uid'      => $this->param['uid'],
                'shop_id'  => 0,
                'add_time' => NOW_TIME,
                'cartid'   => md5(NOW_TIME.rand(100,999)),
                'cardnum'  => $this->param['cardnum'],
                'name'     => $this->param['name'],
                'IDcard'   => $this->param['IDcard'],
                'mobile'   => $this->param['mobile'],
                'type_id'  => $type_id
                );

            if(M('membercard')->add($card)){
                $this->success('添加成功');
            }else{
                $this->error(M()->getError());
            }
    }

    // 首页弹出式广告
    public function getAlertAdv(){
        $type = $this->param['position'];
        if(empty($type)) $type=4;

        $list = M('document')->where(array("type"=>5,"position"=>$type))->field("id,title,cover_id")->order("level DESC,update_time DESC")->select();
        $data = array();
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $tmp['adId'] = $value['id'];
                $tmp['title'] = $value['title'];
                $tmp['activityImg'] = get_cover($value['cover_id'],'path');
                $data[] = $tmp;
            }
        }
        $this->success("success",$data);
    }

    // 删除卡券
    public function delCoupon(){
        if(empty($this->param['uid']) || empty($this->param['coupon'])) $this->error("参数不足");

        if(M('coupon_data')->where(array("id"=>array('in',$this->param['coupon']),"uid"=>$this->param['uid']))->delete()){
            $this->success("success");
        }else{
            $this->error("删除失败");
        }
    }
    // 消费记录
    public function getExpenselog(){
        if(empty($this->param['card_id'])) $this->error("参数不足");
        $where = array('cid'=>$this->param['card_id']);
        if(!empty($this->param['shop_id']) && $this->param['shop_id'] != 0) $where['sid'] = $this->param['shop_id'];
        if(!empty($this->param['type'])) $where['e_type'] = $this->param['type'];

        $list = M('expenselog')->where($where)->order("e_time DESC")->limit("{$this->param['page_start']},{$this->param['pagesize']}")->select();

        $data = array();
        if($list){
            foreach ($list as $key => $value) {
                $tmp = array(
                    'ordernum' => $value['ordernum'],
                    'money'    => $value['money'],
                    'giving'   => $value['giving'],
                    'point'  => $value['e_point'],
                    'coupon'   => empty($value['pid'])? "未使用优惠券":$value['pid'],
                    'type'   => $value['e_type'] ?  "消费":"充值",
                    'is_cash' => $value['is_cash']? "现金支付":"积分支付",
                    'balance'  => $value['balance'],
                    'note'   => $value['note'],
                    );
                $data[] = $tmp;
            }
        }

        $this->success("获取成功",$data);
    }

    // 获取自定义分类
    public function getTagsByUid(){
        $status = 1;
        if(!empty($this->param['uid']) && $this->param['uid'] > 0){
            // 用户登录
            $tags = M('member_tag')->where("uid=".$this->param['uid'])->find();
            if($tags['tags']){
                // 已设置自定义分类
                $data['intag'] = M('category')->where(array("id"=>array("in",$tags['tags']),'status'=>1))->field("id,title")->order("field(id,".$tags['tags'].") ASC")->select();
                $data['notintag'] = M('category')->where(array("id"=>array("not in",$tags['tags']),'status'=>1))->field("id,title")->select();

                $data['intag'] = $data['intag']?$data['intag']:array();
                $data['notintag'] = $data['notintag']?$data['notintag']:array();
                $status = 0;
            }
        }
        if($status){
            // 用户未登录或者用户未设置自定义分类
            $data['intag'] = M('category')->where("status=1")->order("sort ASC")->field("id,title")->select();
        }
        $this->success("获取成功",$data);
    }

    // 设置自定义分类
    public function setTagsByUid(){
        if(empty($this->param['uid']) || empty($this->param['tags'])) $this->error("参数不足");

        $has_save = M('member_tag')->where("uid=".$this->param['uid'])->find();
        if($has_save){
            $r = M('member_tag')->where("uid=".$this->param['uid'])->save(array('tags'=>$this->param['tags']));
        }else{
            $r = M('member_tag')->add(array('uid'=>$this->param['uid'],'tags'=>$this->param['tags']));
        }
        if($r){
            $this->success("success");
        }else{
            $this->error(M()->getError());
        }
    }

    /************   业务员版接口   ************/
    // 业务员登录
    public function salesmanLogin(){
        if(empty($this->param['username']) || empty($this->param['password'])) $this->error("参数不足");

        $User   =   new UserApi;
        $uid    =   $User->login($this->param['username'], $this->param['password'], 1, 3);

        if($uid > 0){
            // 登录成功
            $info = array(
                "uid"     => $uid,
                "username" => $this->param['username'],
                );
            $this->success("登录成功",$info);
        }else{
            // 登录失败
            $msg = $uid == -1 ? "用户不存在或者未审核通过 ":"密码错误";
            $this->error($msg);
        }
    }

    // 获取添加店铺列表
    public function getMyShopList(){
        if(empty($this->param['uid'])) $this->error("参数不足");

        $list = M('shop')->where("add_uid=".$this->param['uid'])->join("LEFT JOIN one_type t on one_shop.type_id=t.type_id")->limit("{$this->param['page_start']},{$this->param['pagesize']}")->select();
        $data = array();
        if($list){
            foreach ($list as $key => $value) {
                $img = get_cover($value['shop_logo_image'],'path');
                $tmp = array(
                    'shop_id'   => $value['id'],
                    'shop_name' => $value['shop_name'],
                    'shop_addr' => $value['shop_addr'],
                    'type_name' => $value['name'],
                    'shop_logo' => $img?$img:'',
                    'shop_color'=> $value['shop_color'],
                    'is_supermarket' =>$value['is_supermarket']
                    );
                $data[] = $tmp;
            }
        }
        $this->success("获取成功",$data);
    }

    // 业务员获取可用总店列表
    public function getAllTypeList(){
        $typelist = M("type")->where("is_private=0")->field("type_id,name")->select();
        $this->success("获取成功",$typelist);
    }

    // 添加店铺
    public function addShopBySalesman(){
        if(empty($this->param['uid'])) $this->error("用户未登录");
        if(empty(trim($this->param['username'])) || empty(trim($this->param['shop_name'])) || empty(trim($this->param['shop_addr']))) $this->error("店铺信息不完整");

        // 总店信息
        if($this->param['type_id'] == "-1" || empty($this->param['type_id'])){
            // 添加新的分类
            if(empty($this->param['type_name']) || empty($_FILES['logo']['name'])) $this->error("新总店信息不可为空");

            // 检查总店名唯一性
            $type = M("type");
            $r = $type->getFieldByName($data['name'],"type_id");
            if($r) $this->error("总店名已经存在,不可重复添加");

            // 上传店铺logo
            $upload = new \Think\Upload();
            $upload->maxSize  = 3145728;
            $upload->exts     = array('jpg','gif','png','jpeg');
            $upload->rootPath = './Uploads/';
            $upload->savePath = 'Picture/';

            $info = $upload->uploadOne($_FILES['logo']);
            $picture = array(
                'path' => '/Uploads/'.$info['savepath'].$info['savename'],
                'url'  => '',
                'md5'  => $info['md5'],
                'sha1' => $info['sha1'],
                'status' => 1,
                'create_time' => NOW_TIME
                );
            $img = M('picture')->add($picture);
            if(!$img) $this->error(M()->getError());

            // 总店信息
            $type_data = array(
                "name" => $this->param['type_name'],
                "shop_cart_image" => $img,
                "shop_logo_image" => $img,
                "shop_color" => $this->param['shop_color'],
                "shop_cart_note" =>$this->param['shop_cart_note'],
            );
            if(!empty($this->param['zhutui'])) $type_data['zhutui'] = $this->param['zhutui'];
            $rt = $type->add($type_data);            
            if($rt){
                $shop_data['type_id'] = $rt;
            }else{
                $this->error($type->getError());
            }
        }else{
            $shop_data['type_id'] = $this->param['type_id'];
        }

        // 用户信息
        /* 调用注册接口注册用户 */
        $User   =   new UserApi;
        $uid    =   $User->register(trim($this->param['username']), "111111","","",2);
        if(0 < $uid){ //注册成功
            $shop_data['uid'] = $uid;
        } else { //注册失败，显示错误信息
            $this->error("注册失败，用户名已存在");
        }

        // 店铺信息
        $shop_data['shop_name'] = $this->param['shop_name'];
        $shop_data['shop_addr'] = $this->param['shop_addr'];
        $shop_data['add_uid']   = $this->param['uid'];
        $shop_data['add_time']  = NOW_TIME;
        if(!empty($this->param['is_supermarket'])) $shop_data['is_supermarket'] = $this->param['is_supermarket'];

        if(M('shop')->add($shop_data)){
            $this->success("添加店铺成功");
        }else{
            $this->error(M('shop')->getError());
        }
    }
    /************   业务员版接口结束   ************/

    /************   商家版接口   ************/
    // 商家登录
    public function shopLogin(){
        if(empty($this->param['username']) || empty($this->param['password'])) $this->error("参数不足");

        $User   =   new UserApi;
        $uid    =   $User->login($this->param['username'], $this->param['password'], 1, 2);

        if($uid > 0){
            // 登录成功
            $data = M('shop')->where(array('uid'=>$uid))->join("LEFT JOIN one_type on one_type.type_id=one_shop.type_id")->find();
            $img = get_cover($data['shop_logo_image'],'path');
            $shop_info = array(
                "uid"     => $uid,
                "username" => $this->param['username'],
                "shop_id" => $data['id'],
                "shop_name" => $data['shop_name'],
                "shop_logo" => $img ? $img : "", 
                "shop_addr" => $data['shop_addr'],
                "shop_status" => $data['status'],
                "type_id"  => $data['type_id'],
                "type_name" => $data['name'],
                "type_color" => $data['shop_color'],
                );
            $this->success("登录成功",$shop_info);
        }else{
            // 登录失败
            $msg = $uid == -1 ? "用户不存在或者未审核通过 ":"密码错误";
            $this->error($msg);
        }
    }
    // 
    /************   商家版接口结束   ************/
    /*
     * 格式化时间戳
     * @param timestamp string  时间戳
     * @param type int 返回类型
     */
    protected function TimeFormat($timestamp,$type="1"){
        $return = "";
        $time = time();
        if($type === 0){
            $different = $time-$timestamp;
            if($different > 259200 ) $return = date("Y年m月d日",$timestamp);
            else if($different > 86400) $return = intval($different/86400) . "天以前";
            else if($different > 3600) $return = intval($different/3600) . "小时以前";
            else if($different > 60) $return = intval($different/60) . "分钟以前";
            else $return = $different . "秒钟以前";
        }else if($type === -1){
            $different = $timestamp-$time;
            if($different <0) $return = "已";
            else if($different > 259200 ) $return = date("Y年m月d日",$timestamp);
            else if($different > 86400) $return = intval($different/86400) . "天之后";
            else if($different > 3600) $return = intval($different/3600) . "小时之后";
            else if($different > 60) $return = intval($different/60) . "分钟之后";
            else $return = $different . "秒钟之后";
        }else if($type == "1"){
            $return = $return = date("Y-m-d h:i:s",$timestamp);
        }else{
            $return = $return = date($type,$timestamp);
        }
        return $return;
    }
    /*
     * 解析json格式数据
     * @param json string  接收post传值
     */
    protected function jsondecode(){
        $json = stripslashes($_POST['json']);
        if(empty($json)) $this->error("缺少json参数");
        $json_arr = json_decode($json,true);

        if(!is_array($json_arr)) $this->error("json格式错误");
        if(!empty($json_arr['page'])){
            $json_arr['pagesize'] = empty($json_arr['pagesize']) ? "10" : $json_arr['pagesize'];
            $json_arr['page_start'] = $json_arr['pagesize']*($json_arr['page']-1);
        }
        return $json_arr;
    }

    /*
     * json 格式返回信息
     * @param msg  string  提示信息
     * @param code integer 返回状态码  默认状态 0 成功    大于0 为错误
     * @param data array   返回数据内容
     * */
    protected function success($msg='',$data=array(),$code='0'){
        $data = $data==null? array():$data;
        $return = array(
            "code" => $code,
            "msg"  => $msg,
            "data" => $data,
        );
        $this->ajaxReturn($return,"json",JSON_UNESCAPED_UNICODE);
        die;
    }
    /* 返回错误 */
    protected function error($msg="",$code="1",$data=array()){
        $this->success($msg,$data,$code);
    }

    public function test(){
        $upload = new \Think\Upload();// 实例化上传类

            $upload->maxSize   =     3145728 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
            $upload->savePath  =     'Bid/'; // 设置附件上传（子）目录

            // 上传文件 
            $info   =   $upload->upload();
            echo json_encode($info);
    }

}